package com.frikinet.gestorepub.web.spring.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.frikinet.gestorepub.web.spring.services.PersistenceService;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class UserLoginInterceptor extends HandlerInterceptorAdapter
{
	private PersistenceService persistenceService;
	
	public UserLoginInterceptor(PersistenceService persistenceService)
	{
		this.persistenceService = persistenceService;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
	{
		UserService userService = UserServiceFactory.getUserService();
		if(modelAndView != null)
		{
			modelAndView.addObject("logged", userService.isUserLoggedIn());
			if(userService.isUserLoggedIn())
			{
				modelAndView.addObject("user", persistenceService.getWebUser(userService.getCurrentUser()));
				modelAndView.addObject("logoutURL", userService.createLogoutURL(request.getRequestURI()));
			}
			else
			{
				modelAndView.addObject("loginURL", userService.createLoginURL(request.getRequestURI()));
			}
		}
	}

}
